package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.cache.BannedUser;
import com.conversationboard.cache.BannedUserCache;
import com.conversationboard.model.User;

@WebServlet(name = "AdminUnbanRangeControllerServlet", urlPatterns = "/Admin/AdminUnbanRangeControllerServlet")
public class AdminUnbanRangeControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -8264864810019410151L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			String adminId = request.getUserPrincipal().getName();

			/* Check if you're authorised */
			User user = User.get(adminId);

			if (!SecurityChecks.passes(request, user, this)) {
				request.setAttribute("message", "You are not authorised to perform that operation.");
				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				dispatcher.forward(request, response);
				return;
			}

			int id = Integer.parseInt(request.getParameter("id").trim());

			List<BannedUser> bannedUsers = BannedUserCache.getBannedUsers(user);
			BannedUser bannedUser = null;

			for (BannedUser u : bannedUsers) {
				if (u.getId() == id) {
					bannedUser = u;
				}
			}

			if (bannedUser == null) {
				return;
			}

			BannedUserCache.unbanPattern(user, id);

			request.setAttribute("message", "Successfully unbanned.");
			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
